package com.ict.ycwl.user.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.ycwl.common.utils.FileUtils;
import com.ict.ycwl.common.utils.MD5Util;
import com.ict.ycwl.common.utils.Transfer;
import com.ict.ycwl.common.web.AjaxResult;
import com.ict.ycwl.user.dao.*;
import com.ict.ycwl.user.pojo.*;
import com.ict.ycwl.user.service.TokenService;
import com.ict.ycwl.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserGroupDao userGroupDao;

    @Autowired
    private RoleOperationDao roleOperationDao;

    @Autowired
    private GroupDao groupDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private OperationDao operationDao;


    //用户登录
    @Override
    public AjaxResult loginByName(String loginName, String password, String captcha, HttpServletRequest httpServletRequest) {


        Map<String,Object> map = new HashMap<>();

       //获取验证码
        String verifyCode = httpServletRequest.getHeader("captcha");
        log.info(verifyCode);


        //解密密码
        String pwd = MD5Util.string2MD5(password);

        if(loginName.isEmpty()){
            return AjaxResult.error("请输入账号");
        }
        else if(password.isEmpty()){
            return AjaxResult.error("请输入密码");
        }
        else if(captcha.isEmpty()){
            return AjaxResult.error("请输入验证码");
        }

        //查找账户是否存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(loginName), User::getLoginName, loginName);
        User user = userDao.selectOne(lambdaQueryWrapper);

        if (user == null) {
            return AjaxResult.error("用户不存在");
        }
        else if (!pwd.equals(user.getPassword())) {
            return AjaxResult.error("密码错误");
        }
        else if(!captcha.equals(verifyCode)){
            return AjaxResult.error("验证码错误");
        }
        else{
            //查找该角色所对应的权限
            LambdaQueryWrapper<RoleOperation> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(RoleOperation::getRoleId,user.getRoleId()).eq(RoleOperation::getStatus,1);
            List<RoleOperation> list = roleOperationDao.selectList(wrapper1);

            String[] operations = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                QueryWrapper<Operation> wrapper2 = new QueryWrapper<>();
                Long operationId = list.get(i).getOperationId();
                wrapper2.eq("operation_id",operationId).select("operation_name");
                Operation operation = operationDao.selectOne(wrapper2);
                operations[i] = operation.getOperationName();
            }

            String token = tokenService.getToken(user);
            map.put("token",token);
            map.put("user",user);
            map.put("operations",operations);
            return AjaxResult.success("登录成功",map);
        }

    }

    //添加用户
    @Override
    public AjaxResult userAdd(String authorization,String phone, String email, String department, String signTime, String workNumber, String userName, Long roleId) {

        //初始化默认密码
        String password = "ycwl123456";

        //从token获取数据
        Long creator = Long.valueOf(JWT.decode(authorization).getClaim("userId").asString());

        //获取当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        String rank = "";
        if (roleId == 2 || roleId == 4 || roleId == 6 ) {
            rank = "基层";
        }else if (roleId ==1 || roleId == 3 || roleId == 7){
            rank = "中层";
        }else if (roleId == 10 || roleId == 8 || roleId == 9){
            rank = "高层";
        }else if (roleId == 5){
            rank = "最高层";
        }

        //初始化User对象
        User user = new User();

        //初始化UserGorup对象
        UserGroup userGroup = new UserGroup();

        //验证手机号码格式是否正确
        boolean validPhone = false;
        if((phone !=null) && (!phone.isEmpty())){
            validPhone = Pattern.matches("^1[3-9]\\d{9}$", phone);
        }

        //验证邮箱格式是否正确
        boolean validEmail = false;
        if ((email != null) && (!email.isEmpty())) {
            validEmail =  Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", email);
        }

        //MD5加密密码
        String pwd = MD5Util.string2MD5(password);

        //查找工号是否存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasText(workNumber), User::getWorkNumber,workNumber);
        User user1 = userDao.selectOne(lambdaQueryWrapper);

        //查找该角色id对应的角色名
        QueryWrapper<Role> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("role_id",roleId);
        Role role = roleDao.selectOne(wrapper1);

        //非空校验
        if (userName.isEmpty()){
            return AjaxResult.error("请输入姓名");
        }
        else if (department.isEmpty()){
            return AjaxResult.error("请选择所属部门");
        }
        else if (signTime.isEmpty()){
            return AjaxResult.error("请选择入职时间");
        }
        else if (roleId == null)
        {
            return AjaxResult.error("请选择角色");
        }
        else if (user1 != null){
            return AjaxResult.error("该工号已存在");
        }
        else if(!email.isEmpty() && !validEmail){
            return AjaxResult.error("邮箱格式错误");
        }
        else if (!validPhone){
            return AjaxResult.error("手机格式错误");
        }
        else{
            //判断班组是否是营销部
            if(department.equals("营销部")){
                user.setRank(rank);
                user.setStatus("1");
                user.setCreateBy(creator);
                user.setUpdateBy(creator);
                user.setUpdateTime(Timestamp.valueOf(sdf.format(date)));
                user.setCreateTime(Timestamp.valueOf(sdf.format(date)));
                user.setDepartment(department);
                user.setLoginName(workNumber);
                user.setUserName(userName);
                user.setPhone(phone);
                user.setEmail(email);
                user.setSignTime(Transfer.transferString2Date(signTime));
                user.setWorkNumber(workNumber);
                user.setPassword(pwd);
                user.setRoleId(roleId);
                user.setPosition(role.getRoleName());
                userDao.insert(user);
            }else{
                //查询该班组所对应的班组ID
                QueryWrapper<Group> wrapper = new QueryWrapper<>();
                wrapper.eq("group_name",department);
                Group group = groupDao.selectOne(wrapper);
                Long groupId = group.getGroupId();

                user.setRank(rank);
                user.setStatus("1");
                user.setCreateBy(creator);
                user.setUpdateBy(creator);
                user.setUpdateTime(Timestamp.valueOf(sdf.format(date)));
                user.setCreateTime(Timestamp.valueOf(sdf.format(date)));
                user.setDepartment(department);
                user.setLoginName(workNumber);
                user.setUserName(userName);
                user.setPhone(phone);
                user.setEmail(email);
                user.setSignTime(Transfer.transferString2Date(signTime));
                user.setWorkNumber(workNumber);
                user.setPassword(pwd);
                user.setRoleId(roleId);
                user.setPosition(role.getRoleName());
                userDao.insert(user);
                userGroup.setUserId(user.getUserId());
                userGroup.setGroupId(groupId);
                userGroupDao.insert(userGroup);
            }
        }

            return AjaxResult.success("添加成功");
        }



    //上传头像
    @Override
    public Object uploadAvatar(MultipartFile photo) throws Exception {
        //头像图片非空校验
//        if(photo == null){
//            return AjaxResult.error(403,"请选择图片");
//        }
//        //上传的图片文件名
//        String originalFileName = photo.getOriginalFilename();
//
//        //获取文件后缀
//        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
//        //生成图片名称
//        String photoName = UUID.randomUUID().toString() + suffix;
//
//        //上传图片
//        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String pre = "/www/wwwroot/ycwl/resource/file";
//        String path  = pre + photoName;
//        try {
//            photo.transferTo(new File(path));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        String path = FileUtils.upload(photo,pre,photo.getOriginalFilename());

        return path;
    }

    @Override
    public AjaxResult userSearch(String department,String userName,String workNumber) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        QueryWrapper<Role> wrapper1 = new QueryWrapper<>();

        if(StringUtils.hasLength(department) && StringUtils.hasLength(userName)){
            wrapper.eq("department",department).eq("user_name",userName).select("user_name","position","work_number","department","avatar_path","rank","role_id").orderByAsc("work_number");
            List<Map<String,Object>> list = userDao.selectMaps(wrapper);
            return AjaxResult.success(list);
        }
        if (StringUtils.hasLength(userName) && StringUtils.hasLength(workNumber)){
            wrapper.eq("work_number",workNumber).eq("user_name",userName).select("user_name","position","work_number","department","avatar_path","rank","role_id").orderByAsc("work_number");
            List<Map<String,Object>> list = userDao.selectMaps(wrapper);
            return AjaxResult.success(list);
        }
        if (StringUtils.hasLength(department) && StringUtils.hasLength(workNumber)){
            wrapper.eq("department",department).eq("work_number",workNumber).select("user_name","position","work_number","department","avatar_path","rank","role_id").orderByAsc("work_number");
            List<Map<String,Object>> list = userDao.selectMaps(wrapper);
            return AjaxResult.success(list);
        }
        if(StringUtils.hasLength(department)){
            wrapper.eq("department",department).select("user_name","position","work_number","department","avatar_path","rank","role_id").orderByAsc("work_number");
            List<Map<String,Object>> list = userDao.selectMaps(wrapper);
            return AjaxResult.success(list);
        }
        else if (StringUtils.hasLength(userName)){
            wrapper.eq("user_name",userName).select("user_name","position","work_number","department","avatar_path","rank","role_id").orderByAsc("work_number");
            List<Map<String,Object>> list = userDao.selectMaps(wrapper);
            return AjaxResult.success(list);

        }
        else if(StringUtils.hasLength(workNumber)){
            wrapper.eq("work_number",workNumber).select("user_name","position","work_number","department","avatar_path","rank","role_id").orderByAsc("work_number");
            List<Map<String,Object>> list = userDao.selectMaps(wrapper);
            return AjaxResult.success(list);
        }
        else{
            wrapper.select("user_name","position","work_number","department","avatar_path","rank","role_id").orderByAsc("work_number");
            List<Map<String,Object>> list = userDao.selectMaps(wrapper);
            return AjaxResult.success(list);
        }

    }

    @Override
    public AjaxResult userUpdatePassword(Long userId, String currentPassword, String newPassword,String confirmPassword) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        User user = userDao.selectOne(wrapper);
        if (currentPassword.isEmpty()){
            return AjaxResult.error("请输入原密码！");
        }
        else if (newPassword.isEmpty()){
            return AjaxResult.error("请输入新密码!");
        }
        else if (!MD5Util.string2MD5(currentPassword).equals(user.getPassword())){
            return AjaxResult.error("原密码不正确!");
        }
        else if (!newPassword.equals(confirmPassword)){
            return AjaxResult.error("两次输入的密码不一致");
        }
        else if (!newPassword.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$")){
            return AjaxResult.error("新密码必须为6-12位的数字+字母组合");
        }
        else{
            UpdateWrapper<User> UpdateWrapper = new UpdateWrapper<>();
            UpdateWrapper.eq("user_id",userId).set("password",MD5Util.string2MD5(newPassword));
            userDao.update(null,UpdateWrapper);
            return AjaxResult.success("修改成功！");
        }

    }

    @Override
    public AjaxResult getUserInfo(String workNumber) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("work_number",workNumber).select("department","phone","role_id","sign_time","user_name","work_number","avatar_path","email","password");
        List<Map<String,Object>> user = userDao.selectMaps(wrapper);
        return AjaxResult.success(user);
    }

    @Override
    public AjaxResult updateUser(String authorization,String phone, String email, String department, String signTime, String workNumber, String userName, Long roleId,String newPassword) {


        //从token获取数据
        Long creator = Long.valueOf(JWT.decode(authorization).getClaim("userId").asString());

        //获取当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //验证手机号码格式是否正确
        boolean validPhone = false;
        if((phone !=null) && (!phone.isEmpty())){
            validPhone = Pattern.matches("^1[3-9]\\d{9}$", phone);
        }

        //验证邮箱格式是否正确
        boolean validEmail = false;
        if ((email != null) && (!email.isEmpty())) {
            validEmail =  Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", email);
        }

        //非空校验
        if (userName.isEmpty()){
            return AjaxResult.error("请输入姓名");
        }
        else if (department.isEmpty()){
            return AjaxResult.error("请选择所属部门");
        }
        else if (signTime.isEmpty()){
            return AjaxResult.error("请选择入职时间");
        }
        else if (roleId == null)
        {
            return AjaxResult.error("请选择角色");
        }
        else if(!email.isEmpty() && !validEmail){
            return AjaxResult.error("邮箱格式错误");
        }
        else if (!validPhone){
            return AjaxResult.error("手机格式错误");
        }
        else if (!newPassword.isEmpty() && !newPassword.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$")){
            return AjaxResult.error("新密码必须为6-12位的数字+字母组合");
        }
        else{

            String rank = "";
            if (roleId == 2 || roleId == 4 || roleId == 6 ) {
                rank = "基层";
            }else if (roleId ==1 || roleId == 3 || roleId == 7){
                rank = "中层";
            }else if (roleId == 10 || roleId == 8 || roleId == 9){
                rank = "高层";
            }else if (roleId == 5){
                rank = "最高层";
            }

            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id",roleId);
            String position = roleDao.selectOne(queryWrapper).getRoleName();
            wrapper.eq("work_number",workNumber).set("user_name",userName).set("department",department).set("email",email).set("phone",phone).set("sign_time",Transfer.transferString2Date(signTime)).set("password", MD5Util.string2MD5(newPassword)).set("role_id",roleId).set("rank",rank).set("position",position).set("update_by",creator).set("update_time",Timestamp.valueOf(sdf.format(date)));
            userDao.update(null,wrapper);
            return AjaxResult.success("更新成功！");
        }

    }

}
